var http = require('http');
var https = require('https');
var qs = require('querystring');
var constant = require('../utils/constant');
var logger = require('../utils/log');

String.prototype.format = function(args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if(args[key]!=undefined){
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        } else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
};

exports.get = function (host,port,path,data,callback) {
    var content = qs.stringify(data);
    var options = {
        hostname: host,
        path: path + '?' + content,
        method:'GET'
    };
    if(port){
        options.port = port;
    }
    logger.debug('request path', options.path);
    var proto = http;
    var req = proto.request(options, function (res) {
        if (callback != null) {
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                logger.debug('request response', chunk);
                var json = JSON.parse(chunk);
                callback(constant.CODE_SUCCESS, json);
            });
        }
    });
    req.on('error', function (e) {
        logger.error('request error', e.message);
        callback(constant.CODE_REQUEST_ERROR, null);
    });
    req.end();
};

exports.get2 = function (url,data,callback,safe) {
    var content = qs.stringify(data);
    url = url + '?' + content;
    logger.debug('request path', url);
    var proto = http;
    if (safe) {
        proto = https;
    }
    var req = proto.get(url, function (res) {
        if (callback != null) {
            // res.setEncoding('utf8');
            res.on('data', function (chunk) {
                logger.debug('request response', chunk);
                var json = JSON.parse(chunk);
                callback(constant.CODE_SUCCESS, json);
            });
        }
    });
    req.on('error', function (e) {
        logger.error('request error', e.message);
        callback(constant.CODE_REQUEST_ERROR, null);
    });
    req.end();
};

exports.post = function (host,port,path,data,callback) {
    var content = JSON.stringify(data);
    var options = {
        hostname: host,
        path: path,
        method:'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(content)
        }
    };
    if(port){
        options.port = port;
    }
    logger.debug('request path', path);
    var proto = http;
    var req = proto.request(options, function (res) {
        if (callback != null) {
            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                logger.debug('request response', chunk);
                var json = JSON.parse(chunk);
                callback(constant.CODE_SUCCESS, json);
            });
        }
    });
    req.on('error', function (e) {
        logger.error('request error', e.message);
        callback(constant.CODE_REQUEST_ERROR, null);
    });
    req.write(content);
    req.end()
};

exports.send = function(response,errcode,data){
    if(data == null){
        data = {};
    }
    data.code = errcode;
    var errmsg = constant.constant[errcode];
    if (errmsg == null) {
        errmsg = 'unknown error';
    }
    data.message = errmsg;
    var jsonstr = JSON.stringify(data);
    response.send(jsonstr);
};